package users

import (
	"context"
	"github.com/zeromicro/go-zero/core/fx"
	"server/chat_room_server/model/mapper"

	"server/chat_room_server/internal/svc"
	"server/chat_room_server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type FriendsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFriendsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FriendsLogic {
	return &FriendsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FriendsLogic) Friends(req *types.FriendsReq) (resp *types.Friends, err error) {
	// todo: add your logic here and delete this line
	id := req.UserId
	db := l.svcCtx.DB
	friends := mapper.Friends(id, db)
	if friends == nil {
		return nil, nil
	}
	var userId int64
	var userName string
	var friends1 []types.FiendsResp

	//fx.Stream{}
	// just 有毒
	fx.From(func(source chan<- any) {
		for _, item := range friends {
			source <- item
		}
	}).Group(func(item any) any {
		friend := item.(mapper.Friend)
		return friend.UserId
	}).ForEach(func(item any) {
		friends11 := item.([]any)
		friend := friends11[0]
		m1 := friend.(mapper.Friend)
		userId = m1.UserId
		userName = m1.UserName
		for _, v := range friends11 {
			m := v.(mapper.Friend)
			fiendsResp := types.FiendsResp{
				UserId:   m.FriendUserId,
				UserName: m.FriendUserName,
			}
			friends1 = append(friends1, fiendsResp)
		}
	})
	return &types.Friends{
		FiendsResps: friends1,
		Id:          userId,
		Name:        userName,
	}, nil
}
